package com.wangxiaonan.inner.controller;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Author: wangxiaonan
 * @Date: 2019/3/28
 **/
@Component
@ServerEndpoint(value = "/websocket/{username}")
public class WebSocketController {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketController.class);

    private static ConcurrentMap<String, WebSocketController> wscm = new ConcurrentHashMap<>();
    private Session session;
    private String username;

    @OnOpen
    public void onOpen(@PathParam(value = "username") String username, Session session) {
        logger.info("用户接入 -------> {}:{}", username, session);
        this.session = session;
        this.username = username;
        WebSocketController wsc = wscm.get(username);
        if (wsc != null) {
            try {
                wsc.session.close(new CloseReason(CloseCodes.CANNOT_ACCEPT, "您的账号在其他客户端登录"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        wscm.put(username, this);
        logger.info("在线人数 -------> {}", wscm.size());
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        if (closeReason.getCloseCode() != CloseCodes.CANNOT_ACCEPT) {
            logger.info("用户下线 -------> {}", session);
            wscm.remove(this.username);
        }
        logger.info("在线人数 -------> {}", wscm.size());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("来自{}的新消息：{}", session.getId(), message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("发生错误", error);
    }

    public void senMessage(String message, String username) {
        WebSocketController wsc;
        try {
            wsc = wscm.get(username);
            if (wsc != null) {
                wsc.session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            logger.error("发送失败 --------> {}", username);
        }

//        for (Map.Entry<String, WebSocketController> s : wscm.entrySet()) {
//            logger.info("发送消息：{}", s.getValue().session);
//            try {
//                s.getValue().session.getBasicRemote().sendText(message);
//            } catch (IOException e) {
//                logger.error("发送失败 --------> {}", s.getValue().session.getId());
//            }
//        }
    }
}
